package cloudContact.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mybeans.factory.RollbackException;
import org.scribe.model.Token;
import org.scribe.oauth.OAuthService;

import cloudContact.FacebookManager;
import cloudContact.MyDAOException;
import cloudContact.SecurityManager;
import cloudContact.DAO.User;
import cloudContact.DAO.UserDAO;

/**
 * Servlet implementation class FacebookOAuth
 */
@WebServlet("/FacebookOAuth")
public class FacebookOAuth extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FacebookOAuth() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Start FacebookOAuth...");

		try {
			if (!SecurityManager.CheckAuthorization(request)) {
				System.out.println("Error: User is not authorized.");
				return;
			}
		} catch (RollbackException e1) {
			e1.printStackTrace();
		} catch (MyDAOException e1) {
			e1.printStackTrace();
		}
		
		OAuthService service = FacebookManager.getOAuthService();
		
		System.out.println("Fetching the Authorization URL...");
		String authorizationUrl = service.getAuthorizationUrl(FacebookManager.EMPTY_TOKEN);
			
		String urlWithSessionID = response.encodeRedirectURL(authorizationUrl);
		response.sendRedirect(urlWithSessionID);

		System.out.println("Finish FacebookOAuth.");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

}
